/**
 * 获取屏幕高度
 * @param callback
 */
function loadWindowHeight(callback) {
    wx.getSystemInfo({
        success: function (res) {
            var windowHeight = res.windowHeight
            console.log("windowHeight: ", res.windowHeight)
            if (callback)
                callback(windowHeight)
        }
    });
}

/**
 * 根据元素ID获取高度
 * @param elementId
 * @param callback
 */
function loadHeightById(elementId, callback) {
    //创建节点选择器
    var query = wx.createSelectorQuery();
    query.select(elementId).boundingClientRect()
    query.exec((res) => {
        var elementHeight = res[0].height;
        if (callback)
            callback(elementHeight)
    })
}

/**
 * 模拟点击事件
 * @param elementId
 */
function elementClick(elementId) {
    var query = wx.createSelectorQuery();
    query.click()
}

/**
 * 根据元素ID获取高度
 * @param elementId
 * @param callback
 */
function loadSizeById(elementId, callback) {
    //创建节点选择器
    var query = wx.createSelectorQuery();
    query.select(elementId).boundingClientRect()
    query.exec((res) => {
        // var elementHeight = res[0].height;
        if (callback)
            callback(res)
    })
}

function getStorageSync(key, defaultValue = "") {
    try {
        const value = wx.getStorageSync(key)
        if (value) {
            return value
        } else {
            return defaultValue
        }
    } catch (e) {
        console.log(e)
        return defaultValue
    }
}

function setStorageSync(key, value) {
    try {
        wx.setStorageSync(key, value)
    } catch (e) {
        console.log("setStorageSync is error", e)
    }
}

function removeSotorageByKey(key) {
    try {
        wx.removeStorageSync(key)
    } catch (e) {
        // Do something when catch error
    }
}

//供使用者调用
function trim(s) {
    return String(trimRight(trimLeft(s)));
}

//去掉左边的空白
function trimLeft(s) {
    if (s == null) {
        return "";
    }
    var whitespace = new String(" \t\n\r");
    var str = new String(s);
    if (whitespace.indexOf(str.charAt(0)) != -1) {
        var j = 0, i = str.length;
        while (j < i && whitespace.indexOf(str.charAt(j)) != -1) {
            j++;
        }
        str = str.substring(j, i);
    }
    return str;
}

//去掉右边的空白
function trimRight(s) {
    if (s == null) return "";
    var whitespace = new String(" \t\n\r");
    var str = new String(s);
    if (whitespace.indexOf(str.charAt(str.length - 1)) != -1) {
        var i = str.length - 1;
        while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1) {
            i--;
        }
        str = str.substring(0, i + 1);
    }
    return str;
}


module.exports = {
    loadWindowHeight: loadWindowHeight,
    loadHeightById: loadHeightById,
    loadSizeById: loadSizeById,
    getStorageSync: getStorageSync,
    setStorageSync: setStorageSync,
    removeSotorageByKey: removeSotorageByKey,
    elementClick: elementClick,
    trim: trim,
}